import { Component, OnInit,OnDestroy } from '@angular/core';

import { Router } from '@angular/router';

import { AppSettings } from '../../app.settings';

import { Util } from '../../utils/util';

import { WordPageService } from './word.page.service';

import { AlertsService } from '../../modules/ng2-alerts';

declare var $:any;
@Component({
  selector: 'app-word',
  templateUrl: './word.page.html',
  styleUrls: ['./word.page.css'],
  providers: [WordPageService]
})
export class WordPage implements OnInit {
  constructor(private util: Util, private service: WordPageService, private alertsService: AlertsService,private router:Router) {
  }

  cat: any;

  param:any = {
    rows: 100,
    start: 0,
    categoryId: '',
    type: 'hot'
  };
  // category option
  option:any = {
    defaultText: true

  };

  vm: any = {
    "loading": true,
    "data": [],
    "type": 'word',
    "fileName": "",
    "click": (param) => {

      let index = param.dataIndex;

      let data:any = this.vm.data[index];

      Object.assign(data,{type:this.param.type});

      // 保存
      this.util.sessionStore().set('wordDetail', data);

      this.router.navigate(['word', data['words']]);

      // console.log(param);
    }

  };



  ngOnInit() {

     /*if (this.util.sessionStore().has('word')) {

      let _store = this.util.sessionStore().get('word');

      Object.assign(this.param, _store.param);

      console.log(_store);

      if (_store.cat && (typeof _store.cat.wholeName != "undefined")) {
        this.option.cat = _store.cat.wholeName == '' ? "/" : _store.cat.wholeName;
      }

      this.getHttp(this.param);

    }*/

    $('#wordChart').height($(document.body).height()-110);

  }

  ngOnDestroy(){
    this.util.sessionStore().set('word', { param: this.param, cat: this.cat });
    if(this.sub){
      this.sub.unsubscribe();
    }
  }

  // 类型切换
  typeChange(_type) {

    console.log(_type);

    if (this.param.type == _type) {
      return;
    }

    this.param.type = _type;
    this.vm.loading = true;
    this.getHttp(this.param);

  }


  // out handel
  handleUpdated(cat) {

    console.log(cat);

    console.log(this.cat);

    if (!this.util.equals(this.cat, cat)) {

      this.cat = Object.assign({},cat);

      this.vm.fileName = this.cat.wholeName+"词云下载";

      this.param.categoryId = this.cat.categoryId;

      this.vm.loading = true;
      this.getHttp(this.param);
    }

  }


  // xhr
  sub: any;
  getHttp(param) {

    if (this.vm.loading && this.sub) {
      this.sub.unsubscribe();
    }


    this.sub = this.service.getWord(param).subscribe((res: any) => {

      this.vm.data = res.data.value;

      this.vm.loading = false;

    }, (err: any) => {

      this.vm.loading = false;

      this.alertsService.create('info', err.msg);
    });
  }
}
